<template>
  <view class="page">
    <!-- 头部 -->
    <view class="header">
      <view class="count-chip">共 {{ totalCount }} 份</view>
      <button class="clear-btn" @click="clearCart">清空</button>
    </view>

    <!-- 空状态 -->
    <view v-if="items.length === 0" class="empty">
      <view class="empty-icon">
        <uni-icons type="cart" color="#D1D5DB" :size="64" />
      </view>
      <view class="empty-title">还没有已点菜品</view>
      <view class="empty-desc">快去首页挑选喜欢的菜吧～</view>
      <button class="go-index" @click="goIndex">去首页</button>
    </view>

    <!-- 购物车内容 -->
    <view v-else class="cart-wrapper">
      <!-- 可滚动列表 -->
      <scroll-view class="cart-scroll" scroll-y>
        <view class="list">
          <view class="item" v-for="it in items" :key="it.id" @click="goToDishDetail(it)">
            <image class="thumb" :src="getImageSrc(it.image)" mode="aspectFill" />
            <view class="meta">
              <view class="name">{{ it.name || '未命名菜品' }}</view>
              <view class="controls" @click.stop>
                <button class="ctrl" @click="decrement(it)">
                  <uni-icons type="minus" color="#111827" :size="20" />
                </button>
                <text class="count">{{ it.count }}</text>
                <button class="ctrl" @click="increment(it)">
                  <uni-icons type="plus" color="#111827" :size="20" />
                </button>
                <button class="remove" @click="removeItem(it)">
                  <uni-icons type="trash" color="#EF4444" :size="20" />
                </button>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 固定底部按钮 -->
      <view class="footer">
        <view class="actions">
          <button class="btn secondary" @click="goIndex">继续点菜</button>
          <button class="btn primary" @click="sendOrder">发送订单</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import cart from '@/common/cart.js'
import { getImageSrc } from '@/common/image.js'

const items = ref([])

function loadCart() {
  items.value = cart.getCart()
  updateTabBadge()
}

function increment(it) {
  const next = (Number(it.count) || 0) + 1
  items.value = cart.updateCount(it.id, next)
  updateTabBadge()
}

function decrement(it) {
  const next = (Number(it.count) || 0) - 1
  if (next <= 0) {
    items.value = cart.removeItem(it.id)
  } else {
    items.value = cart.updateCount(it.id, next)
  }
  updateTabBadge()
}

function removeItem(it) {
  uni.showModal({
    title: '移除菜品',
    content: `确定将 "${it.name || '菜品'}" 从已点中移除吗？`,
    success(res) {
      if (res.confirm) {
        items.value = cart.removeItem(it.id)
        updateTabBadge()
      }
    }
  })
}

function clearCart() {
  if (items.value.length === 0) return
  uni.showModal({
    title: '清空已点',
    content: '确定清空所有已点菜品吗？',
    success(res) {
      if (res.confirm) {
        items.value = cart.clear()
        updateTabBadge()
      }
    }
  })
}

function goIndex() {
  uni.switchTab({ url: '/pages/index/index' })
}

function sendOrder() {
  if (items.value.length === 0) {
    uni.showToast({ title: '没有可发送的菜品', icon: 'none' })
    return
  }
  uni.showModal({
    title: '发送订单',
    content: `确认发送当前 ${totalCount.value} 份菜品吗？`,
    async success(res) {
      if (res.confirm) {
        try {
          const orderRes = await uniCloud.callFunction({
            name: 'food-order',
            data: {
              action: 'create-order',
              data: {
                dishes: items.value,
                remarks: ''
              }
            }
          })
          
          if (orderRes.result && orderRes.result.code === 200) {
            uni.showToast({ title: '订单已发送', icon: 'success' })
            cart.clear()
            items.value = []
            updateTabBadge()
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/ordered/ordered'
              })
            }, 1000)
          } else {
            uni.showToast({ title: orderRes.result?.message || '订单发送失败', icon: 'none' })
          }
        } catch (err) {
          uni.showToast({ title: '订单发送失败', icon: 'none' })
        }
      }
    }
  })
}

function goToDishDetail(item) {
  uni.navigateTo({
    url: `/pages/dish-detail/dish-detail?id=${item.id}`
  })
}

const totalCount = computed(() => {
  return items.value.reduce((sum, it) => sum + (Number(it.count) || 0), 0)
})

onShow(() => {
  loadCart()
})

function updateTabBadge() {
  cart.syncTabBadge(2)
}
</script>

<style lang="scss" scoped>
$page-padding: 32rpx;
$radius-lg: 16rpx;
$border: 1rpx solid #eef2f7;
$text-muted: #6b7280;

.page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f8fafc;
}

.header {
  padding: 20rpx $page-padding;
  display: flex;
  align-items: center;
  gap: 12rpx;
  background: #fff;
  border-bottom: $border;
  flex-shrink: 0;

  .count-chip {
    padding: 10rpx 18rpx;
    font-size: 28rpx;
    color: #0f172a;
    background: #eef2f7;
    border-radius: 999rpx;
  }

  .clear-btn {
    margin-left: auto;
    padding: 12rpx 22rpx;
    font-size: 28rpx;
    color: #ef4444;
    background: #fff;
    border: 1rpx solid #fecaca;
    border-radius: 999rpx;
    line-height: 1;
  }

  .clear-btn:active {
    background: #fef2f2;
  }
}

.empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 $page-padding;
  text-align: center;

  .empty-icon {
    margin-bottom: 24rpx;
  }

  .empty-title {
    font-size: 32rpx;
    color: #111827;
    font-weight: 700;
    margin-bottom: 8rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: $text-muted;
    margin-bottom: 32rpx;
  }

  .go-index {
    background: #007aff;
    color: #fff;
    border: none;
    border-radius: 12rpx;
    padding: 20rpx 36rpx;
    font-size: 28rpx;
  }
}

.cart-wrapper {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.cart-scroll {
  flex: 1;
  overflow-y: auto;
}

.list {
  padding: $page-padding $page-padding 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;

  .item {
    background: #fff;
    border: $border;
    border-radius: $radius-lg;
    display: flex;
    gap: 20rpx;
    padding: 20rpx;
    align-items: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

    .thumb {
      width: 140rpx;
      height: 140rpx;
      border-radius: 12rpx;
      background: #f3f4f6;
      flex-shrink: 0;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 16rpx;
    }

    .name {
      font-size: 30rpx;
      font-weight: 700;
      color: #0f172a;
    }

    .controls {
      display: flex;
      align-items: center;
      gap: 8rpx;
    }

    .ctrl {
      width: 56rpx;
      height: 56rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fff;
      border: 1rpx solid #e5e7eb;
      border-radius: 12rpx;
      padding: 0;
    }

    .count {
      min-width: 56rpx;
      text-align: center;
      font-size: 28rpx;
      color: #111827;
    }

    .remove {
      margin-left: 8rpx;
      width: 56rpx;
      height: 56rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fff5f5;
      border: 1rpx solid #fecaca;
      border-radius: 12rpx;
      padding: 0;
    }
  }
}

.footer {
  flex-shrink: 0;
  background: #fff;
  padding: 16rpx $page-padding;
  padding-bottom: max(16rpx, env(safe-area-inset-bottom));
  border-top: $border;
  box-shadow: 0 -6rpx 20rpx rgba(0, 0, 0, 0.06);

  .actions {
    display: flex;
    gap: 16rpx;
  }

  .btn {
    flex: 1;
    min-width: 0;
    border: none;
    border-radius: 12rpx;
    padding: 22rpx 0;
    font-size: 28rpx;
  }

  .btn.secondary {
    background: #eef2f7;
    color: #111827;
  }

  .btn.primary {
    background: #10b981;
    color: #fff;
  }
}
</style>
